# -*- coding: utf-8

import pyglet
from pyglet.gl import *

import math

class Camera(object):
    def __init__(self, position, scale=1, angle=0):
        self.x, self.y = position
        self.angle = angle
        self.scale = scale

    def zoom(self, factor):
        self.scale *= factor

    def pan(self, length, angle):
        self.x += length * math.cos(angle)
        self.y += length * math.sin(angle)

    def rotate(self, angle):
        self.angle += angle

    def focus(self, win_width, win_height):
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        aspect = win_width / float(win_height)
        gluOrtho2D(-self.scale * aspect, # left
                    self.scale * aspect, # right
                   -self.scale,          # bottom
                    self.scale)          # top

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        gluLookAt(self.x, self.y, 1.0,  # camera x, y, z
                  self.x, self.y, -1.0, # look at x, y, z
                  math.sin(self.angle), math.cos(self.angle), 0.0)
    
    def hud_mode(self, width, height):
    
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluOrtho2D(0, width, 0, height)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

time_elapsed = 0

def test():
    win_width = 640
    win_height = 480
    
    window = pyglet.window.Window(win_width, win_height)
    camera = Camera((1.5,1.5), scale=2)

    fps_display = pyglet.clock.ClockDisplay()

    glClearColor(0, 1, 0, 0)

    verts = pyglet.graphics.vertex_list(4,
                                        ("v2f", (1, 2,
                                                 2, 2,
                                                 2, 1,
                                                 1, 1))
                                        )

    @window.event
    def on_draw():
        window.clear()
        camera.focus(window.width, window.height)
        verts.draw(GL_POLYGON)
        camera.hud_mode(window.width, window.height)
        fps_display.draw()

    def update(dt):
        global time_elapsed
        time_elapsed += dt
        camera.rotate(5.0*dt)
        camera.scale = 2 + math.sin(3*time_elapsed)

    pyglet.clock.schedule_interval(update, 1/60.0)
    pyglet.clock.set_fps_limit(60)
    pyglet.app.run()
    

if __name__ == "__main__":
    test()

    
